<?php

namespace app\ports\controller\publics;

use think\Db;
use think\Log;

/**
 * 实时计算 - 达标
 */
class Primarys
{
	/**
	 * 对象实例
	 * @var object
	 */
	protected static $instance;

	/**
	 * 获取实例对象
	 * @return object
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	public function handles()
	{
		try {
			$default = "2023-10-01";
			$current = date("Y-m-d");
			if (strtotime($default) > strtotime($current)) exit();
			$times = date("Y-m");
			$money = $this->trans_money($times);
			$transMoney = bcmul($money, '5', 2);
			$temps = Template::instance()->stands_calc(5);
			if ($temps) {
				$tmp = [];
				foreach ($temps as $val) {
					$p_stands_money = 0;
					$p_stands_money = bcmul((string)$val['money'], (string)$val["nums"], 2);
					if ($transMoney >= $p_stands_money) {
						$tmp[] = $val["code"];
					}
				}
				if ($tmp) {
					// 匹配达标模板
					foreach ($tmp as $v) {
						$this->_store_upgrade_cords($v, \app\ports\constants\TeamsConstants::PRIMARY_ACCOUNT_NUM_ID, $times);
					}
				}
			}
		} catch (\Exception $e) {
			Log::write($e->getMessage());
		}
	}


	/**
	 * 存储晋级记录
	 * @param  $id  等级ID
	 * @param  $pid 达标计算代理ID
	 * @param  $times 计算时间
	 * @param  $data  交易数据
	 */
	public function _store_upgrade_cords($lev_code, $pid, $times)
	{
		if (!empty($lev_code) && !empty($pid) && !empty($times)) {
			try {
				$times = strtotime($times);
				$option = [
					"agid"		=> $pid,
					"lev_code"	=> $lev_code,
					"times"		=> $times,
					"isReals"	=> 2
				];
				$check = Db::name("bonus_upgrade")->where($option)->count();
				if (!$check) {
					$option["createTime"] = time();
					Db::name("bonus_upgrade")->insert($option);
				}
			} catch (\Exception $e) {
				echo $e->getMessage();
			}
		}
	}

	/**
	 * 获取平台交易
	 * @param string $times
	 */
	public function trans_money($times)
	{
		$sum = "0.00";
		$times = strtotime($times);
		$table = "fd_bonus_calc_trans_" . date("Y", $times);
		$isExist = Db::query("SHOW TABLES like '" . $table . "'");
		if ($isExist) {
			$sum  = Db::table($table)
				->where("times = " . $times)
				->sum("transAmt");
		}
		return $sum;
	}
}
